package com.springboot.astra.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
@Component
@ConfigurationProperties("jwt.config")
public class JwtUtils {
    //签名key
    private String key;
    //签名失效时间
    private long ttl;
    /**
     * 设置认证token
     * id：登录用户di
     * subject：登录用户名
     */
    public String createJwt(String id, String name, Map<String,Object> map){
        //设置失效时间
        long now = System.currentTimeMillis();
        long exp = now+ttl;
        //创建jwtbuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,key)
                .addClaims(map)
                .setExpiration(new Date(exp));
        return  jwtBuilder.compact();
    }

    /**
     *
     * @param id
     * @param name
     * @return
     */
    public String createJwt(String id, String name){
        //设置失效时间
        long now = System.currentTimeMillis();
        long exp = now+ttl;
        //创建jwtbuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,key)
                .setExpiration(new Date(exp));
        return  jwtBuilder.compact();
    }
    /**
     * 解析token
     */
    public Claims parseJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getTtl() {
        return ttl;
    }

    public void setTtl(Long ttl) {
        this.ttl = ttl;
    }
}
